package edu.buaa.resourceManager.controller;

import edu.buaa.resourceManager.helper.Utils;
import edu.buaa.resourceManager.search.Search;
import edu.buaa.resourceManager.store.JsonStore;
import edu.buaa.resourceManager.store.StoreDB;
import edu.buaa.resourceManager.vo.ResourcePath;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryparser.classic.ParseException;
import org.slf4j.Logger;
import spark.Route;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created by song on 17-6-22.
 */
public class SearchController
{
    private static Logger log = Utils.getDevLogger();

    public static Route Page = (request, response) -> {
        response.type("text/html");
        return new Scanner(ImportController.class.getResourceAsStream("/html/main.html"), "UTF-8").useDelimiter("\\A").next();
    };

    public static Route Latest = (request, response) -> {
        List<ResourcePath> result = StoreDB.getInstance().getFilesByTimeDes();
        return JsonStore.getInstance().json.toJson(result);
    };

    public static Route StringSearch = (request, response) -> {
        String txt = request.params(":text");
        log.debug("search: {}",txt);
        try {
            List<Document> result = Search.getInstance().search(txt);
            List<ResourcePath> resourcePaths = new ArrayList<>();
            for (Document doc : result) {
                log.debug(doc.get(Search.FIELD_SHA512));
//FIXME                resourcePaths.add(Search.fromDoc(doc));
            }
            return JsonStore.getInstance().json.toJson(resourcePaths);
        }catch (ParseException ignore){
//            e.printStackTrace();
            return "[]";
        }
    };
}
